from django.template import Context, loader, TemplateDoesNotExist
from django.http import HttpResponse
from django.shortcuts import render_to_response
import os
import sys
import logging
import feedparser

from sitedefinitions import FeedSite
from advert import Advert

       

def index(request):
    logging.debug('started root request')
    return index2(request,'')
    
def index2(request, domain):
    logging.debug('started specific site request for [' + domain + ']')
    
    #try:
        # Check for a test explicit domain call
    if cmp(domain, '') == 0:        
        hostheader =  request.META["HTTP_HOST"]        
    else:
        hostheader =  domain

    logging.debug('Executing process for [' + hostheader + ']')
    if hostheader == 'initdata':
        return initdata(request)

    currentsite = FeedSite()
    currentsite.Load(hostheader)

    python_wiki_rss_url = currentsite.FeedURL 

    feed = feedparser.parse( python_wiki_rss_url )
    rootpath = os.path.dirname(__file__)
    templatepath = os.path.join(rootpath, 'rbtest/index.html')
    logging.debug('Attempting to load template from ' + templatepath)
   
    #print templatepath
    resp = render_to_response('index.html', {'feed': feed["items"], 'currentsite':currentsite, 'advertposition':3})
    return resp
    #return HttpResponse(templatepath)
    #except TemplateDoesNotExist:
    #    return HttpResponse("Failed to load the specifid template ")        
    #except:
        #logging.error(sys.exc_info()[0])        
    #    return HttpResponse("Exception occurred ")# + str(sys.exc_info()[0]))
        
def initdata(request):
    logging.debug('Initialising data')
    s = FeedSite()
    s.TestSetup()
    logging.debug('Initialisation completed')
    return HttpResponse('Initialisation complete')
    
